package com.demo.steammanagement.service;


import com.demo.steammanagement.model.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private IUsersService iUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        Users users =null;
        // 假设可以通过某种方式判断identifier是用户名还是邮箱
        if (username.contains("@")) { // 简单的邮箱检测
            users = this.iUserService.getUserByEmail(username);
        } else {
            users = this.iUserService.getUserByUsername(username);
        }

        if (users == null) {
            throw new UsernameNotFoundException("用户未找到: " + username);
        }


        // 获取用户的角色列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        if ("1".equals(users.getUserRole())) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else {
            if(users.getStatus() == 0){
                throw new AccountStatusException("账号冻结: " + username) {
                };
            }
            if("2".equals(users.getUserRole())){
                authorities.add(new SimpleGrantedAuthority("ROLE_USER2"));
            }
            if("3".equals(users.getUserRole())){
                authorities.add(new SimpleGrantedAuthority("ROLE_USER3"));
            }
//            // 获取用户的账户过期日期
//            LocalDateTime accountExpirationDate = users.getAccountExpirationDate();
//            // 获取当前时间
//            LocalDateTime now = LocalDateTime.now();
//            // 比较两个日期
//            if (accountExpirationDate == null || !accountExpirationDate.isAfter(now)) {
//                throw new AccountExpiredException("账号已过期: " + username);
//            }

        }

        // 创建 UserDetails 对象
        UserDetails userDetails = new User(
                users.getAccount(),
                users.getPassword(),
                authorities
        );
        return userDetails;
    }
}